package mysql

import (
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/cheneylau/components/web-server/global/global-util"
	"gitee.com/cheneylau/components/web-server/model"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
)

var BeegoDB orm.Ormer
var GormDB *gorm.DB

func init() {
	initMYSQL()
	initGormDB()
}

func getDsn() string {
	cnf, err := global_util.AppConfig()
	global_util.CheckErr(err, "ini config not exist!")

	runmode := cnf.String("runmode")
	dbHost := cnf.String(runmode+"::mysql_db_host")
	dbPort := cnf.String(runmode+"::mysql_db_port")
	dbUser := cnf.String(runmode+"::mysql_db_user")
	dbPassword := cnf.String(runmode+"::mysql_db_password")
	dbName := cnf.String(runmode+"::mysql_db_name")

	url := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&loc=Local",dbUser,dbPassword,dbHost,dbPort,dbName)
	return url
}

func initGormDB()  {
	db1 := mysql.New(mysql.Config{
		DriverName: "mysql",
		DSN: getDsn(),
	})
	db, err := gorm.Open(db1, &gorm.Config{})
	if err != nil {
		panic(err)
	}
	sqlDB, _ := db.DB()
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetConnMaxLifetime(time.Hour)
	GormDB = db
	db.AutoMigrate(&model.TestModel{})
}

func initMYSQL()  {
	dsn := getDsn()
	err := orm.RegisterDataBase("default", "mysql",dsn , 30)
	if err != nil {
		panic(err)
	}

	mds := []interface{}{
		new(model.TestModel),
	}

	// register model
	orm.RegisterModel(mds...)

	// create table
	orm.RunSyncdb("default", false, true)
	// debug sql
	//orm.Debug = true

	BeegoDB = orm.NewOrm()
	BeegoDB.Using("default")
}


func MySQLQuery(sql string, args ...interface{}) ([]orm.Params, error) {
	var items []orm.Params
	_, err := BeegoDB.Raw(sql, args...).Values(&items)
	if err != nil {
		return nil, err
	}
	return items, nil
}

func MySQLQueryValueWithField(field string,sql string , args ...interface{}) (string, error) {
	items, err := MySQLQuery(sql, args...)
	if err != nil {
		return "", err
	}
	if len(items) == 0 {
		return "", errors.New("未查询到数据")
	}
	return items[0][field].(string), nil
}

func MySQLQueryOne(sql string , args ...interface{}) (orm.Params, error) {
	items, err := MySQLQuery(sql, args...)
	if err != nil {
		return nil, err
	}
	if len(items) == 0 {
		return nil, errors.New("未查询到数据")
	}
	return items[0], nil
}

func MySQLQueryToJson(sql string, args ...interface{}) (string, error) {
	items , err := MySQLQuery(sql, args...)
	if err != nil {
		return "", err
	}
	b, err := json.Marshal(items)
	if err != nil {
		return "", err
	}
	return string(b), nil
}

func MySQLQueryWithOrmer(o orm.Ormer,sql string, args ...interface{}) ([]orm.Params, error) {
	var items []orm.Params
	_, err := o.Raw(sql, args...).Values(&items)
	if err != nil {
		return nil, err
	}
	return items, nil
}

func MySQLQueryToJsonWithOrmer(o orm.Ormer,sql string, args ...interface{}) (string, error) {
	items , err := MySQLQueryWithOrmer(o, sql, args...)
	if err != nil {
		return "", err
	}
	b, err := json.Marshal(items)
	if err != nil {
		return "", err
	}
	return string(b), nil
}

